package com.sjtfreaks.jet.movieapp.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.sjtfreaks.jet.movieapp.Bean.WeatherData;
import com.sjtfreaks.jet.movieapp.R;
import com.sjtfreaks.jet.movieapp.adapter.WeatherAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jet on 2018-10-16.
 */

public class WeiFragment extends Fragment {
    private ListView mListView;
    private List<WeatherData> mList = new ArrayList<>();
    public static WeiFragment newInstance(String name){
        Bundle args = new Bundle();
        args.putString("name", name);
        WeiFragment fragment = new WeiFragment();
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wei,null);
        findView(view);
        return view;

    }

    private void findView(View view) {
        mListView = (ListView) view.findViewById(R.id.mListView);
        //清理列表进行刷新
        //mList.clear();
        //获取天气数据 宁波代码：101210401
        String url = "https://www.tianqiapi.com/api/?version=v1&city=%E5%AE%81%E6%B3%A2&ip=27.193.13.255";
        RxVolley.get(url, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                //解析json
                parsingJson(t);
                //Toast.makeText(getActivity(),t, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void parsingJson(String t) {
        //解析json
        try {
            JSONObject jsonObject = new JSONObject(t);
            JSONArray jsonList = jsonObject.getJSONArray("data");

            for (int i = 0; i<jsonList.length();i++){
                JSONObject json = (JSONObject) jsonList.get(i);
                WeatherData data = new WeatherData();

                data.setWeek(json.getString("week"));
                data.setWea(json.getString("wea"));
                data.setTem1(json.getString("tem1"));
                data.setTem2(json.getString("tem2"));
                data.setDate(json.getString("date"));

                mList.add(data);

            }
            WeatherAdapter adapter = new WeatherAdapter(getActivity(),mList);
            mListView.setAdapter(adapter);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
}
